import numpy as np

def length( v ):
    return np.sqrt(np.dot(v,v))
    
def uv_to_dir( u,v):
    dir = np.array([u, v, np.sqrt(1-u**2-v**2) ])
    return dir

def uv_to_theta_phi( u,v ):
    x,y,z = uv_to_dir(u,v).tolist()
    theta = np.arccos(z)
    phi = np.arctan2(y,x)
    return theta, phi
import string
import random
def id_generator(size=6, chars=string.ascii_lowercase):
    return ''.join(random.choice(chars) for x in range(size))

from ROOT import *

def plot_in_TH2F( data, title, bins=(100,100) ):
    
    x = data[:,0]
    y = data[:,1]
    
    canvas_name = id_generator()
    c = TCanvas( canvas_name,title,0,0,500,500)
    
    xmin = x.min()
    xmax = x.max()
    ymin = y.min()
    ymax = y.max()

    h_name = id_generator()
    
    h = TH2F( h_name, title, bins[0],xmin,xmax,bins[1],xmin,xmax)
    
    for i in data:
        h.Fill(i[0],i[1])
    
    c.cd()
    h.Draw("colz")
    c.Update()
    
    return h,c

def plot_in_TH1F( data, title, bins=100 ):
    
    x = data
    
    canvas_name = id_generator()
    c = TCanvas( canvas_name,title,0,0,500,500)
    
    xmin = x.min()
    xmax = x.max()
    
    h_name = id_generator()
    
    h = TH1F( h_name, title, bins,xmin,xmax)
    
    for i in data:
        h.Fill(i)
    
    c.cd()
    h.Draw()
    c.Update()
    
    return h,c


def plot_in_TGraph2D( data, title ):
    raise NotImplementedError("This function is buggy, so I declare it as not implemented. DN")
    
    canvas_name = id_generator()
    canvas_title = canvas_name
    c = TCanvas( canvas_name,title,0,0,500,500)
    
    g = TGraph2D()
    
    for index,d in enumerate(data):
        g.SetPoint( index, *d)
    
    g.SetMarkerStyle(20)
    g.SetTitle(title)
    
    c.cd()
    g.Draw("pcol")
    c.Update()
    
    return g,c
    
def plot_chids( run, s=80):
    
    pd = run['photonData']
    event_headers=run['corsikaEventHeaders']
    
    import plotters
    import matplotlib.pyplot as plt
    # find max event_id
    event_ids = pd['event_id']
    max_event_id = int(event_ids.max())

    camplotter = plotters.CamPlotter('cam', dpi=s, s=s)

    
    for i in range(max_event_id):
        ids = np.where(pd['event_id']==i)[0]
        pixels = pd['chid'][ids].astype(int)
        ph_in_pix = np.zeros(1440)
        for pix in pixels:
            ph_in_pix[pix] += 1
        print "event=%d  photons=%d" % (i, len(ids))
        print pixels
        print ("energy=%f GeV" % event_headers[i]['total energy in GeV'])
        
        #calculating core distace:
        core = np.array(event_headers[i]['core location for scattered events in cm: (x,y)'][0])
        core_dist= np.sqrt((core*core).sum())
        print "core dist=%f m" % (core_dist/100,)
        camplotter(ph_in_pix)
        plt.xlim(-22,22)
        plt.ylim(-22,22)
        raw_input('next?')

